<template>
  <div>
    <!-- 2. 卡片主体 -->
    <el-card>
          <!-- 2.1 搜索 & 添加 -->
          <!-- 搜索栏 -->
      <el-row :gutter="20" style="margin-bottom: 15px">
      <el-col :span="6">
        <el-input
        v-model="queryInfo.templateName"
        placeholder="请输入模板名称"
        clearable
        @clear="getTemplateList"
        @keyup.enter="getTemplateList"
        />
      </el-col>

      <el-col :span="6">
        <el-button type="primary" icon="Search" @click="getTemplateList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
            <el-button @click="handleAdd" >添加</el-button>

      </el-col>
      </el-row>

      <!-- 2.2 表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%; margin-top: 15px"
      >
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="templateName" label="名称" />

        <el-table-column prop="description" label="备注" />
        <el-table-column label="启用状态">
          <template #default="{ row }">
            <el-switch v-model="row.isActive" active-value="1" inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <!-- <el-button type="danger" size="small" @click="handleDelete(row)" v-if="row.status == 0">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改角色配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="processRef" :model="templateForm" :rules="rules" label-width="100px">
            <el-form-item label="模板名称" prop="templateName">
               <el-input v-model="templateForm.templateName" placeholder="请输入模板名称" />
            </el-form-item>
            <!-- 动态下拉框部分 -->
            <el-form-item 
                v-for="(select, index) in templateForm.dynamicSelects" 
                :key="index"
                :label="'选项 ' + (index + 1)"
                :prop="'dynamicSelects.' + index + '.value'"
                :rules="{ required: true, message: '请选择角色', trigger: 'change' }"
            >
                <el-select v-model="select.value" placeholder="请选择" style="width: 80%">
                <el-option
                    v-for="item in select.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
                </el-select>
                <el-button @click="removeSelect(index)" type="danger" style="margin-left: 10px">移除</el-button>
            </el-form-item>
            
            <el-form-item>
                <el-button @click="addSelect" type="primary" >添加</el-button>
            </el-form-item>

            <el-form-item label="备注" prop="remarks">
               <el-input v-model="templateForm.remarks" placeholder="请输入备注" />
            </el-form-item>
    
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import{approvalTemplateList,approvalTemplateAdd,approvalTemplatePublish} from '../../request/process/template'


import{roleList} from '../../request/role'

//加载出来下拉选项
const selectOptions= ref([])
const getRoleList = async () => {
	let data =await roleList({pageNum:1,pageSize:10});
    selectOptions.value = []
    data.records.forEach(item => {
        selectOptions.value.push({
            value: item.id,
            label: item.name
        })
    })
}

// 查询参数
const queryInfo = reactive({
  templateName: '',
  pageNum: 1,
  pageSize: 10
})
const tableData = ref([])
// 获取列表
const getTemplateList = async () => {
	let data =await approvalTemplateList(queryInfo);
	tableData.value = data
}
getTemplateList()

//重置查询条件

function resetQuery(){
	queryInfo.templateName='';
	queryInfo.pageNum=1;
	queryInfo.pageSize=10
	getTemplateList()
}

const rules = reactive({
	templateName: [
      { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    remarks: [
      { required: true, message: '请输入备注', trigger: 'blur' }
    ]
})

const open = ref(false)
const title = ref('添加')
const templateForm = reactive({
    dynamicSelects: [], // 动态下拉框数据
    processName: '',
    remarks: ''
})

function handleAdd(){
    getRoleList()
    templateForm.dynamicSelects = []
    open.value = true
    title.value = '添加'
}

const processRef = ref(null);
function submitForm(){
    processRef.value.validate((valid) => {
        if (valid) {
            if(templateForm.dynamicSelects.length==0){
                ElMessage.error('请配置流程')
                return
            }
            let selectList = templateForm.dynamicSelects;
            let approvalNodeList = [];
            let levelNumber = 1

            selectList.forEach(each=>{
              approvalNodeList.push({nodeLevel:levelNumber,approverValue:each.value})
              levelNumber++
            })
            templateForm.approvalNodeList = approvalNodeList
            // 提交表单数据
            console.log('表单数据:', templateForm);
            approvalTemplateAdd(templateForm).then(res=>{
                ElMessage.success('添加成功')
                    getTemplateList()
                    cancel()
                    //processRef.value.resetFields()
            })

        } else {
            console.log('校验失败');
        }
    });
}
function cancel(){
    open.value = false
    title.value = '添加'
    processRef.value.resetFields()
    // 清空表单数据
    Object.assign(templateForm, {});
    templateForm.selectOptions = [];
    templateForm.defineLevels = [];
}
//添加下拉框
function addSelect() {
    templateForm.dynamicSelects.push({
    value: '', // 选中的值
    options: [...selectOptions.value] // 下拉框选项

    });
}
// 删除下拉框
function removeSelect(index) {
    templateForm.dynamicSelects.splice(index, 1);
}

function handleStatusChange(row) {
  let text = row.isActive === "1" ? "停用" : "启用"
  ElMessageBox.confirm("确认要" + text + row.templateName+ "吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await approvalTemplatePublish(row.templateId,row.isActive)
          // 点击确定后的操作
          ElMessage.success("操作已确认");
          
        })
        .catch(() => {
          row.isActive = row.isActive === "1" ? "0" : "1"
          // 点击取消后的操作
          //ElMessage.info("已取消操作");
        });
}

</script>

<style scoped>
.breadcrumb {
  margin-bottom: 15px;
}
</style>